/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxinline.servico;

import br.com.foxinline.modelo.Curso;
import br.com.foxinline.modelo.Disciplina;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.Query;

/**
 *
 * @author laverson
 */
@Stateless
public class DisciplinaServico extends ServicoGenerico<Disciplina> {

    public DisciplinaServico() {
        super(Disciplina.class);
    }

    public List<Disciplina> pesquisar(Disciplina entity) {

        String sql = "Select d from Disciplina d ";

        Curso curso = entity.getCurso();

        if (curso != null && curso.getId() != null) {
            sql += "JOIN d.curso c";
        }

        sql += " where ";

        if (entity.getCodigo() != null && !entity.getCodigo().equals("")) {
            sql += " lower(d.codigo) like lower(:codigo) AND ";
        }

        sql += " d.ocupaSala = :ocupaSala AND ";

        if (entity.getNome() != null && !entity.getNome().equals("")) {
            sql += " lower(d.nome) like lower(:nome) AND ";
        }

        if (curso != null && curso.getId() != null) {
            sql += " c = :curso AND";
        }

        sql += " 1=1 ";

        Query query = getEntityManager().createQuery(sql);

        if (entity.getCodigo() != null && !entity.getCodigo().equals("")) {
            query.setParameter("codigo", "%" + entity.getCodigo().replace(" ", "%") + "%");
        }

        query.setParameter("ocupaSala", entity.isOcupaSala());

        if (entity.getNome() != null && !entity.getNome().equals("")) {
            query.setParameter("nome", "%" + entity.getNome().replace(" ", "%") + "%");
        }

        if (curso != null && curso.getId() != null) {
            query.setParameter("curso", curso);
        }

        return query.getResultList();
    }

    public List<Disciplina> pesquisar(Curso entity) {

        String sql = "Select d from Disciplina d JOIN d.curso c where ";

        if (entity != null && entity.getId() != null) {
            sql += " c = :curso AND ";
        }

        sql += " 1=1 ";

        Query query = getEntityManager().createQuery(sql);

        if (entity != null && entity.getId() != null) {
            query.setParameter("curso", entity);
        }

        return query.getResultList();
    }
}
